package com.example.demo.controller;

import com.example.demo.entity.MyTable;
import com.example.demo.service.MyTableService1;
import com.example.demo.service.MyTableService2;
import com.example.demo.service.multi.MultiThreadQueryService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author yfy2001
 * @date 2024/6/7 13:58
 */
@RestController
public class MyTableController {

    @Resource
    private MyTableService1 myTableService1;

    @Resource
    private MyTableService2 myTableService2;

    @Resource
    private MultiThreadQueryService multiThreadQueryService;

    @GetMapping("getData")
    @Cacheable(cacheNames = {"getData"},key = "#id")
    public List<MyTable> getData(Integer id) {
        List<MyTable> result = new ArrayList<>();
        List<MyTable> dataList1 = myTableService1.getDataFromAllTablesById(id);
        List<MyTable> dataList2 = myTableService2.getDataFromAllTablesById(id);
        result.addAll(dataList1);
        result.addAll(dataList2);
        return result;
    }

    @GetMapping("getDataAsync")
    @Cacheable(cacheNames = {"getData"},key = "#id")
    public List<MyTable> getDataAsync(Integer id) throws ExecutionException, InterruptedException {
        CompletableFuture<List<MyTable>> future = multiThreadQueryService.asyncQuery(id);
        return future.get();
    }
}
